package insert;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class AjoutProduitServlet
 */
public class AjoutProduitServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AjoutProduitServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		RequestDispatcher dis;
		Connection con = null;
		Context namingContext;
		Map<Integer, String> types = new LinkedHashMap<Integer, String>();
		
		//Si je ne suis pas connecté alors je suis redirigé
		Integer membre = (Integer)session.getAttribute("user_id");
		if(membre == null){
			dis = request.getRequestDispatcher("/login.jsp");
			dis.forward(request, response);
			return;
		}
		
		try {
			namingContext = new InitialContext();
			DataSource dataSource = (DataSource)namingContext.lookup("java:comp/env/jdbc/MiniIBay");
			con = dataSource.getConnection();
		
			PreparedStatement pstmt = con.prepareStatement("SELECT * FROM `type_produit`");
			ResultSet rs = pstmt.executeQuery();
			
			while(rs.next()){
				types.put(rs.getInt("id_type"), rs.getString("nom"));
			}
			
			request.setAttribute("types", types);
			dis=request.getRequestDispatcher("ajoutproduit.jsp");
			dis.forward(request,response);
			
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(con != null){
				try {
					con.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String intitule = null;
		String desc = null;
		String idType = null;

		List<String> erreur = new LinkedList<String>();
		
		if(!erreur.isEmpty()){ //Donn�es du formulaire incorrectes, renvoie au formulaire
			request.setAttribute("erreur", erreur);
			RequestDispatcher dis=request.getRequestDispatcher("ajoutproduit.jsp");
			dis.forward(request,response);
		}else{ 
			//Donn�es correctes, envoie de la requ�te � la base de donn�es
			Connection con;
			Context namingContext;
			PreparedStatement pstmt;
			
			try{
				//Etablissons la connexion à la bdd :
				namingContext = new InitialContext();
				DataSource dataSource = (DataSource)namingContext.lookup("java:comp/env/jdbc/MiniIBay");
				con = dataSource.getConnection();
				
				//Commençons par gérer l'upload
				FileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory);
				String fileName = null;
				try {
					List items = upload.parseRequest(request);
					Iterator iterator = items.iterator();
					while (iterator.hasNext()) {
						FileItem item = (FileItem) iterator.next();
						if (item.isFormField()) {
							String tmpName = item.getFieldName();
							
							if(tmpName.equals("type"))
								idType = item.getString();
							else if (tmpName.equals("desc"))
								desc = item.getString();
							else if (tmpName.equals("intitule"))
								intitule = item.getString();
						} else {
							FileItem photo = item;
							//Quel est le type du produit ?
					    	PreparedStatement typeProduit = con.prepareStatement("SELECT nom FROM type_produit WHERE id_type = ?");
					    	typeProduit.setInt(1, Integer.parseInt(idType));
					    	ResultSet rs = typeProduit.executeQuery();
							rs.next();
							String nomType = rs.getString("nom");
					    	typeProduit.close();
					    	
					    	//Et maintenant l'upload à proprement parler :
					    	 fileName = photo.getName();
					    	 if(! fileName.isEmpty()) {
					    		 System.out.println(fileName);
			                     String root = getServletContext().getRealPath("/");
			                     File path = new File(root + "/images/"+nomType);
			                     if (!path.exists()) {
			                         boolean status = path.mkdirs();
			                     }
	
			                     File uploadedFile = new File(path + "/" + fileName);
			                     fileName = nomType+"/"+fileName;
			                     try {
									photo.write(uploadedFile);
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
					    	 }
						}
					}
				} catch (FileUploadException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				if(intitule == null || desc == null || idType == null){
					erreur.add("Un des champs obligatoire n'est pas rempli");
				}
					
				if(intitule.length() > 80) 	erreur.add("La taille de l'intitule est trop longue (maximum 80 caract&egrave;res)");
				
				pstmt = con.prepareStatement("INSERT INTO `produit` (`id_type`, `intitule`, `description`, `photo`) VALUES (?, ?, ?, ?)");
				pstmt.setInt(1, Integer.parseInt(idType));
				pstmt.setString(2, intitule);
				pstmt.setString(3, desc);
				pstmt.setString(4, fileName);
				
				pstmt.executeUpdate();
				
				response.sendRedirect("../home");
			}catch(NamingException e){
				// TODO Auto-generated catch block
				e.printStackTrace();
				response.sendRedirect("../home");
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				response.sendRedirect("../home");
			}
			
		}
	}
}